package listener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

import entity.User;
import util.sessionUtil;

//@WebListener
public class servletrequest_listener implements ServletRequestListener
{
	//在线用户list
	private ArrayList<User> userList;

	@Override
	public void requestDestroyed(ServletRequestEvent sre)
	{
//		System.out.println("============requestDestroyed=============");
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre)
	{
//		System.out.println("============requestInitialized=============");
		HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
		String sessionID = request.getSession().getId();
//		System.out.println("sessionID:" + sessionID);
		
		userList = (ArrayList<User>)sre.getServletContext().getAttribute("userList");
		if(userList == null)
		{
			userList = new ArrayList<User>();
		}
		
		//如果找不到相应的用户
		if(sessionUtil.getUserBySeesionID(userList,sessionID) == null)
		{
			User user = new User();
			user.setSessionID(sessionID);
			user.setIp(request.getRemoteAddr());
			user.setFirstTime(new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date()));
			
			userList.add(user);
		}
		sre.getServletContext().setAttribute("userList", userList);
	}

}
